package com.seecen.controller;

import com.seecen.utils.SnowflakeUtils;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/resource")
public class ResourceController {

    @SneakyThrows
    @PostMapping("/upload")
    public String upload(MultipartFile[] files, HttpServletRequest request, HttpServletResponse response) {
        // 上传到项目的部署的路径下面
        String rootPath = request.getServletContext().getRealPath("/");
        File localFile = new File(rootPath + "upload");
        if(!localFile.exists()) localFile.mkdirs();
        for (MultipartFile multipartFile : files) {
            String originalFilename = multipartFile.getOriginalFilename();
            // 截取文件名后缀
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 生成新的文件名，并且防止重复
            String newFilename = SnowflakeUtils.nextId() + suffix;
            multipartFile.transferTo(new File(localFile, newFilename));
        }
        return "success";
    }


    @SneakyThrows
    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletRequest request, HttpServletResponse response) {
        String rootPath = request.getServletContext().getRealPath("/");
        File localFile = new File(rootPath + "upload", filename);
        if(!localFile.exists()) {
            // 响应前端404
            response.sendError(HttpStatus.NOT_FOUND.value());
            return;
        }
        // 设置响应头,如果不设置，默认在浏览器中打开
        response.setHeader("Content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(localFile), 1024 * 1024 * 5);
        byte[] buffer = new byte[1024 * 512];
        int len = 0;
        while((len = bis.read(buffer)) != -1) {
            response.getOutputStream().write(buffer, 0, len);
        }
        response.getOutputStream().flush();
    }
}
